package com.yidiandao.business.utils;

import static com.yidiandao.business.constant.Common.BAIDU;
import static com.yidiandao.business.constant.Common.GAODE;
import static com.yidiandao.business.constant.Common.SOUGOU;
import static com.yidiandao.business.constant.Common.TENGXUN;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.TextView;

import com.yidiandao.business.R;
import com.yidiandao.business.constant.Common;
import com.yidiandao.business.ui.widget.dialog.LoadingDialog;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

/**
 * 获取手机里的地图软件 并由用户选择开启导航
 */
public class LocationChooseUtils implements View.OnClickListener {
    private List<String> mApps;
    private double mLatitude;
    private double mLongitude;
    private Activity mActivity;
    private String mAddress;
    private AlertDialog mDialog;
    private LoadingDialog mLoadingDialog;

    /**
     * 遍历手机内指定的地图软件
     */
    private void getAllApps(Context context) {
        mApps = new ArrayList<>();
        PackageManager pManager = context.getPackageManager();
        // 获取手机内所有应用
        List<PackageInfo> packlist = pManager.getInstalledPackages(0);
        for (int i = 0; i < packlist.size(); i++) {
            PackageInfo pak = packlist.get(i);
            // 判断是否为非系统预装的应用程序
            // 这里还可以添加系统自带的，这里就先不添加了，如果有需要可以自己添加
            // if()里的值如果<=0则为自己装的程序，否则为系统工程自带
            //            if ((pak.applicationInfo.flags & pak.applicationInfo.FLAG_SYSTEM) <= 0) {
            String packageName = pak.packageName;
            //添加 百度 高德 搜狗地图   腾讯暂不支持uri调用
            if (packageName.equals(BAIDU)
                    || packageName.equals(GAODE)
                    || packageName.equals(SOUGOU)
                    || packageName.equals(TENGXUN)) {
                mApps.add(packageName);
            }
        }
    }

    /**
     * 获取遍历后指定的地图软件
     */
    private List<String> getApps() {
        return mApps;
    }

    /**
     * 反地理编码 获取经纬度
     *
     * @param address 要反地理编码的地址
     */
    private void parseAddress(Context context, String address) {
        //反地理编码
        Geocoder geocoder = new Geocoder(context);
        try {
            List<Address> addressList = geocoder.getFromLocationName(address, 5);
            if (null != addressList && addressList.size() != 0) {
                mLatitude = addressList.get(0).getLatitude();
                mLongitude = addressList.get(0).getLongitude();
            }
        } catch (Exception e) {
            e.printStackTrace();
            mLoadingDialog.dismiss();
        }
    }

    /**
     * 获取纬度
     */
    private double getLatitude() {
        return mLatitude;
    }

    /**
     * 获取经度
     */
    private double getLongitude() {
        return mLongitude;
    }

    /**
     * 解析地址并提示用户
     *
     * @param address 要解析的地址
     */
    public void showGuideDialog(final Activity activity, final String address) {
        mActivity = activity;
        mAddress = address;
        mLoadingDialog = new LoadingDialog(mActivity);
        mLoadingDialog.show();
        new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        //解析地址
                        parseAddress(activity, address);
                        //获取手机内安装的建议地图软件
                        getAllApps(activity);
                        activity.runOnUiThread(
                                new Runnable() {
                                    @Override
                                    public void run() {
                                        showDialog();
                                    }
                                });
                    }
                })
                .start();
    }

    /**
     * 提示用户选择导航的dialog
     */
    private void showDialog() {
        mLoadingDialog.dismiss();
        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
        View rootView = View.inflate(mActivity, R.layout.dialog_location_guide, null);
        builder.setView(rootView);
        TextView tvDialogBaidu = (TextView) rootView.findViewById(R.id.tv_dialog_baidu);
        TextView tvDialogGaode = (TextView) rootView.findViewById(R.id.tv_dialog_gaode);
        TextView tvDialogTengxun = (TextView) rootView.findViewById(R.id.tv_dialog_tengxun);
        TextView tvDialogSougou = (TextView) rootView.findViewById(R.id.tv_dialog_sougou);

        mDialog = builder.create();

        setOpenEnable(tvDialogBaidu, Common.BAIDU);
        setOpenEnable(tvDialogGaode, Common.GAODE);
        setOpenEnable(tvDialogTengxun, Common.TENGXUN);
        setOpenEnable(tvDialogSougou, Common.SOUGOU);

        if (mDialog != null && !mDialog.isShowing()) {
            mDialog.show();
        }
    }

    @Override
    public void onClick(View v) {
        mDialog.dismiss();
        switch (v.getId()) {
            case R.id.tv_dialog_baidu: {
                try {
                    //移动APP调起Android百度地图方式举例
                    Intent intent =
                            Intent.getIntent(
                                    "intent://map/geocoder?address="
                                            + mAddress
                                            + "#Intent;scheme=bdapp;package=com.baidu.BaiduMap;"
                                            + "end");
                    mActivity.startActivity(intent);
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
                break;
            }
            case R.id.tv_dialog_gaode: {
                StringBuilder stringBuilder =
                        new StringBuilder("androidamap://navi?sourceApplication=")
                                .append(UIUtils.getString(R.string.app_name_release));
                stringBuilder.append("&poiname=").append(mAddress);
                stringBuilder
                        .append("&lat=")
                        .append(getLatitude())
                        .append("&lon=")
                        .append(getLongitude())
                        .append("&dev=")
                        .append("0") //是否偏移(0:lat 和 lon 是已经加密后的,不需要国测加密; 1:需要国测加密)
                        .append("&style=")
                        .append(
                                "2"); //导航方式 0 速度快; 1 费用少; 2 路程短; 3 不走高速；4 躲避拥堵；5 不走高速且避免收费；6
                // 不走高速且躲避拥堵；7 躲避收费和拥堵；8 不走高速躲避收费和拥堵
                Intent intent =
                        new Intent(
                                Intent.ACTION_VIEW,
                                android.net.Uri.parse(stringBuilder.toString()));
                intent.setPackage(Common.GAODE);
                mActivity.startActivity(intent);
                break;
            }
            case R.id.tv_dialog_tengxun: {
                String string =
                        "qqmap://map/routeplan?type=drive&to="
                                + mAddress
                                + "&tocoord="
                                + getLatitude()
                                + ","
                                + getLongitude();
                Intent it = new Intent(Intent.ACTION_VIEW, android.net.Uri.parse(string));
                it.setPackage(Common.TENGXUN);
                mActivity.startActivity(it);
                break;
            }
            case R.id.tv_dialog_sougou: {
                Uri uri = Uri.parse("geo:" + getLatitude() + "," + getLongitude());
                Intent it = new Intent(Intent.ACTION_VIEW, uri);
                it.setPackage(Common.SOUGOU);
                mActivity.startActivity(it);
                break;
            }
        }
    }

    /**
     * 设置打开按钮的状态
     */
    private void setOpenEnable(TextView textView, String packetName) {
        if (getApps().contains(packetName)) {
            textView.setBackgroundResource(R.drawable.bg_red_normal);
            textView.setTextColor(UIUtils.getColor(R.color.white));
            textView.setOnClickListener(this);
        } else {
            textView.setBackgroundResource(R.drawable.bg_gray_normal);
            textView.setTextColor(UIUtils.getColor(R.color.text_color_7));
            textView.setOnClickListener(null);
        }
    }
}
